// pages/game/game-rice-item/game-rice-item.js
var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var mySetInterval;
const bgm = wx.getBackgroundAudioManager();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLandId: 0,
    showWater: false,
    showFertilition: false,
    //水稻成熟状态
    rice_state: 0,
    //果实数量
    gainVal: 0,
    showMask: false,
    showProp: false,
    showHaverNum: false,
    list: [1, 2, 3, 4],
    //浇水动画消失时间
    waterTime: 1200,
    //施肥动画消失时间
    shifeiTime: 1200,
    //浇水提示
    waterHint: false,
    //浇水后数字动画
    waterNumHint: false,
    //提示水不够
    showWaterOverlay: false,
    //提示肥料不够
    showManureOverlay: false,
    //任务领取提示
    showTaskProp: false,
    //成熟提示
    showFinishHint: false,
    //收获提示
    showHint: false,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var userLandId = options.userLandId;
    var step1 = wx.getStorageSync("step1");
    if (step1 == '') {
      step1 = 0
    }
    this.setData({
      showlead1: step1,
      userLandId: userLandId
    })
    this.getData();
    this.getGoodsData();
    this.backmusic()
  },
  //商品数据
  getGoodsData() {
    let that = this;
    util.gameRequest(api.FindPropGoodsBuyList).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          goodsList: res.data
        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //点击进入详情购买
  onItemClick: util.throttle(function(e) {
    var goodsid = e.currentTarget.dataset.id;
    util.toClass('/pages/details/details', {
      goodsid: goodsid
    })
  }),
  //数据
  getData() {
    let that = this;
    util.gameRequest(api.LandDetail, {
      userLandId: that.data.userLandId
    }).then(function(res) {
      that.dealData(res);
    });
  },
  //无加载框数据
  getDataNoLoading() {
    let that = this;
    util.gameRequestNoLoading(api.LandDetail, {
      userLandId: that.data.userLandId
    }).then(function(res) {
      that.dealData(res);
    });
  },
  //处理数据
  dealData: function(res) {
    var that = this;
    if (res.errno == 0) {
      //需要时间
      var needTime = res.data.needTime;
      //道具时间
      var propAdditionTime = res.data.propAdditionTime;
      //开始时间
      var startTime = res.data.startTime;
      //适配苹果时间格式
      startTime = startTime.replace(/-/g, "/");
      //开始时间戳
      var startTimeTamps = new Date(startTime).getTime();
      console.log("开始时间---", startTime)
      //当前时间
      var nowTime = util.formatTimeDetails(new Date());
      nowTime = nowTime.replace(/-/g, "/");
      //当前时间戳
      var nowTimeTamps = new Date(nowTime).getTime();
      console.log("当前时间---", nowTime)
      var countTime = needTime * 1000 - (nowTimeTamps - startTimeTamps + propAdditionTime * 1000);
      console.log("倒计时---", countTime)

      that.setData({
        bean: res.data,
        time: countTime
      })
      if (res.data.status == 3) {
        //未成熟
        var retio = res.data.ratio
        if (retio >= 0 && retio <= 20) {
          that.setData({
            rice_state: 1,
            statename: '胚芽萌芽'
          })
        } else if (retio > 20 && retio <= 40) {
          that.setData({
            rice_state: 2,
            statename: '插秧吐绿'
          })
        } else if (retio > 40 && retio <= 60) {
          that.setData({
            rice_state: 3,
            statename: '生长分蘖'
          })
        } else if (retio > 60) {
          that.setData({
            rice_state: 4,
            statename: '谷秒抽穗'
          })
        }
      } else if (res.data.status == 4) {


        that.setData({
          rice_state: 5,
          statename: '成熟',
          showFinishHint: true
        })
        if (res.data.gainVal > 0) {
          //果实数量大于0，可以收获
          that.onAnimationText();
          that.setData({
            gainVal: res.data.gainVal
          })
        }
      }
    } else {
      util.myToast(res.errmsg)
    }
    //每次加载前先清空
    clearInterval(mySetInterval);
    mySetInterval = setInterval(function(e) {
      //当前时间戳
      var nowTims = new Date(util.formatTimeDetails(new Date()).replace(/-/g, "/")).getTime();
      // console.log("自然成长时间---", (nowTims - startTimeTamps)/1000);
      // console.log("道具时间---", propAdditionTime);
      // console.log("总时间---", needTime);
      var normalTime = (nowTims - startTimeTamps) / 1000;
      var propTime = propAdditionTime;

      var progress = ((normalTime + propAdditionTime) / needTime) * 100
      progress = progress.toFixed(0);

      if (progress >= 100) {
        progress = 100;
        clearInterval(mySetInterval);
      }
      // console.log("进度条---", progress)
      that.setData({
        progress: progress
      })
      var retio = progress
      if (retio >= 0 && retio <= 20) {
        that.setData({
          rice_state: 1,
          statename: '胚芽萌芽'
        })
      } else if (retio > 20 && retio <= 40) {
        that.setData({
          rice_state: 2,
          statename: '插秧吐绿'
        })
      } else if (retio > 40 && retio <= 60) {
        that.setData({
          rice_state: 3,
          statename: '生长分蘖'
        })
      } else if (retio > 60 && retio < 100) {
        that.setData({
          rice_state: 4,
          statename: '谷秒抽穗'
        })
      } else if (retio > 100) {

        that.setData({
          rice_state: 5,
          showFinishHint: true,
          statename: '成熟'
        })

      }
    }, 1000)
  },
  //关闭成熟提示
  onCloseFinishHint(e) {
    var step4 = wx.getStorageSync("step4");
    if (step4 == '') {
      step4 = 0
    }
    this.setData({
      showFinishHint: false,
      showlead4: step4
    })
  },
  //点击签到

  onAttendance: util.throttle(function(e) {
    var time = util.formatTime(new Date())
    this.getAttendanceData(time);
  }),
  //签到
  getAttendanceData(attendanceDate) {
    let that = this;
    util.gameRequest(api.Attendance, {
      attendanceDate: attendanceDate
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        util.myToast("签到成功")
        var msg = res.data;
        var arr = msg.split(":")
        that.getTaskListNoLoadingData();
        var step2 = wx.getStorageSync("step2");
        if (step2 == '') {
          step2 = 0
        }
        that.setData({
          showlead2: step2,
          showMask: false,
          showProp: false,
          title: '签到成功',
          gethint: arr[0],
          showlead5: 1

        })
        wx.setStorageSync("step5", 1);
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //点击作物弹窗
  onClickRice() {
    var hours = this.data.time / 1000 / 60 / 60;
    var unit="小时";
    
    hours = hours.toPrecision(1);
    if(hours<1){
      hours=hours*60;
      unit="分钟"
    }
    util.myToast("作物处于" + this.data.statename + "期,预计" + hours+unit + "成熟,预计产量" + this.data.bean.gainVal + "颗")
  },
  //点击领取订单任务
  getShopProp: util.throttle(function(e) {
    this.getPropData(2, '订单积分');
  }),
  //点击领取分享任务
  getShareProp: util.throttle(function(e) {
    this.getPropData(3, '邀请赠送');
  }),
  //领取订单和邀请好友道具
  getPropData(receiveType, title) {
    let that = this;
    util.gameRequest(api.TaskReceive, {
      receiveDate: util.formatTime(new Date()),
      receiveType: receiveType
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        var msg = res.data;
        var arr = msg.split(":")
        that.setData({
          showMask: false,
          showTaskProp: true,
          showProp: false,
          title: title,
          gethint: arr[0]
        })
        that.getDataNoLoading();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //关闭领取道具提示弹窗
  onCloseSharePropHint(e) {
    var step4 = wx.getStorageSync("step4");
    if (step4 == '') {
      step4 = 0
    }
    this.setData({
      showTaskProp: false,
      showlead4: step4
    })
  },
  //可收获动画
  onAnimationText() {
    var attentionAnim = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease',
      delay: 0
    })
    //设置循环动画
    this.attentionAnim = attentionAnim
    var next = true;
    setInterval(function() {
      if (next) {
        //根据需求实现相应的动画
        this.attentionAnim.translateY(5).step()
        next = !next;
      } else {
        this.attentionAnim.translateY(-5).step()
        next = !next;
      }
      this.setData({
        //导出动画到指定控件animation属性
        attentionAnim: attentionAnim.export()
      })
    }.bind(this), 2000)
  },
  //浇水提示动画
  onAnimationWater() {
    var attentionAnimWater = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease',
      delay: 0
    })
    //设置循环动画
    this.attentionAnimWater = attentionAnimWater
    var next = true;
    setInterval(function() {
      if (next) {
        //根据需求实现相应的动画
        this.attentionAnimWater.translateY(10).step()
        next = !next;
      } else {
        this.attentionAnimWater.translateY(-10).step()
        next = !next;
      }
      this.setData({
        //导出动画到指定控件animation属性
        attentionAnimWater: attentionAnimWater.export()
      })
    }.bind(this), 2000)
  },
  //点击浇水
  onWater: util.throttle(function(e) {
    this.getWaterData();
  }),
  //浇水
  getWaterData() {
    let that = this;
    util.gameRequest(api.LandWater, {
      userLandId: that.data.userLandId
    }).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          hint_txt: res.data.wateringNum,
          showlead2: 1,
          showMask: false,
          showProp: false
        })
        //关闭第2步的新手引导
        wx.setStorageSync("step2", 1);
        //开启第3步施肥引导
        var step3 = wx.getStorageSync("step3");
        if (step3 == '') {
          step3 = 0
        }
        that.setData({
          showlead3: step3
        })
        if (that.data.rice_state == 5 && !that.data.showFertilition) {
          //已经成熟
          that.setData({
            waterTop: -178,
            waterRight: -112,
            showWater: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showWater: false,
              waterHint: false
            })
            that.waternumAnima();
          }, that.data.waterTime)
        } else if (that.data.rice_state == 4 && !that.data.showFertilition) {
          that.setData({
            waterTop: -95,
            waterRight: -23,
            showWater: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showWater: false
            })
            that.waternumAnima();
          }, that.data.waterTime)
        } else if (that.data.rice_state == 3 && !that.data.showFertilition) {
          that.setData({
            waterTop: -56,
            waterRight: -23,
            showWater: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showWater: false
            })
            that.waternumAnima();
          }, that.data.waterTime)
        } else if (that.data.rice_state == 2 && !that.data.showFertilition) {
          that.setData({
            waterTop: -20,
            waterRight: -23,
            showWater: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showWater: false
            })
            that.waternumAnima();
          }, that.data.waterTime)
        } else if (that.data.rice_state == 1 && !that.data.showFertilition) {
          that.setData({
            waterTop: 10,
            waterRight: -23,
            showWater: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showWater: false
            })
            that.waternumAnima();
          }, that.data.waterTime)
        }
        setTimeout(function(e) {
          that.getDataNoLoading();
        }, 1500)

      } else if (res.errno == 508) {
        //水滴不够
        that.setData({
          showWaterOverlay: true

        })

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //关闭水滴不够提示
  onCloseNoWaterHint(e) {
    this.setData({
      showWaterOverlay: false,
      showManureOverlay: false
    })
  },
  //关闭水滴不够提示,并领取道具
  onReceiveProp(e) {
    this.setData({
      showWaterOverlay: false,
      showManureOverlay: false,
    })
    this.getTaskListData();
  },
  //点击施肥
  onFertilization: util.throttle(function(e) {
    this.getManuretData();
  }),
  //施肥
  getManuretData() {
    let that = this;
    util.gameRequest(api.LandManure, {
      userLandId: that.data.userLandId
    }).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          hint_txt: res.data.manureingNum,
          showlead3: 1,
          showMask: false,
          showProp: false
        })
        //关闭第三步
        wx.setStorageSync("step3", 1);
        if (that.data.rice_state == 5 && !that.data.showWater) {
          //已经成熟
          that.setData({
            waterTop: -178,
            waterRight: -112,
            showFertilition: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showFertilition: false
            })
            that.waternumAnima();
          }, that.data.shifeiTime)
        } else if (that.data.rice_state == 4 && !that.data.showWater) {
          that.setData({
            waterTop: -95,
            waterRight: -23,
            showFertilition: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showFertilition: false
            })
            that.waternumAnima();
          }, that.data.shifeiTime)
        } else if (that.data.rice_state == 3 && !that.data.showWater) {
          that.setData({
            waterTop: -56,
            waterRight: -23,
            showFertilition: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showFertilition: false
            })
            that.waternumAnima();
          }, that.data.shifeiTime)
        } else if (that.data.rice_state == 2 && !that.data.showWater) {
          that.setData({
            waterTop: -20,
            waterRight: -23,
            showFertilition: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showFertilition: false
            })
            that.waternumAnima();
          }, that.data.shifeiTime)
        } else if (that.data.rice_state == 1 && !that.data.showWater) {
          that.setData({
            waterTop: 10,
            waterRight: -23,
            showFertilition: true
          })
          //2秒后消失
          setTimeout(function(e) {
            that.setData({
              showFertilition: false
            })
            that.waternumAnima();
          }, that.data.shifeiTime)
        }
        setTimeout(function(e) {
          that.getDataNoLoading();
        }, 1500)
      } else if (res.errno == 509) {
        that.setData({
          showManureOverlay: true
        })
      } else {
        util.myToast(res.errmsg)
      }
    });
  },

  //领取道具
  onGetProp: util.throttle(function(e) {
    this.getTaskListData();
  }),
  //任务列表
  getTaskListData() {
    let that = this;
    util.gameRequest(api.TaskParam).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          showMask: true,
          taskBean: res.data,
          showlead1: 1
        })
        //关闭第一步的新手引导
        wx.setStorageSync("step1", 1);
        that.showPopAnima();
        //开启第二步
        var step5 = wx.getStorageSync("step5");
        if (step5 == '') {
          step5 = 0
        }
        that.setData({
          showlead5: step5,
        })
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //任务列表无加载框
  getTaskListNoLoadingData() {
    let that = this;
    util.gameRequestNoLoading(api.TaskParam).then(function(res) {
      if (res.errno == 0) {
        that.setData({
          taskBean: res.data
        })
        that.getDataNoLoading();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //关闭弹窗和蒙版
  onCloseMask(e) {
    this.setData({
      showMask: false,
    })
    this.closePopAnima()
  },
  //收获大米
  onHarvest: util.throttle(function(e) {

    this.setData({
      showHint: true,
      showlead4: 1
    })
    //关闭第4步的新手引导
    wx.setStorageSync("step4", 1);
  }),
  onClosehint(e) {
    this.setData({
      showHint: false
    })
  },
  onSure: util.throttle(function(e) {
    this.setData({
      showHint: false
    })
    this.getFinishData();
  }),
  //收获
  getFinishData() {
    let that = this;
    util.gameRequest(api.LandFinish, {
      userLandId: that.data.userLandId
    }).then(function(res) {
      if (res.errno == 0) {
        that.haverAnima();
      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  // 收获大米动画
  haverAnima: function(e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease'
    })
    that.animation = animation
    animation.translateY(0).step()
    that.setData({
      animationRiceData: animation.export(),
      showHaverNum: true,
    })
    animation.translateY(-80).step()
    that.setData({
      animationRiceData: animation.export(),

    })
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationRiceData: animation.export(),
        showHaverNum: false,
      })
      wx.navigateBack({
        delta: 1
      })
    }, 800)
  },
  // 浇水后动画
  waternumAnima: function(e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease'
    })
    that.animation = animation
    animation.translateY(0).step()
    that.setData({
      animationwaternumData: animation.export(),
      waterNumHint: true,
    })
    animation.translateY(-80).step()
    that.setData({
      animationwaternumData: animation.export(),

    })
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationwaternumData: animation.export(),
        waterNumHint: false,
      })
    }, 800)
  },
  //弹出动画
  showPopAnima: function(e) {
    // 用that取代this，防止不必要的情况发生
    var that = this;
    // 创建一个动画实例
    var animation = wx.createAnimation({
      // 动画持续时间
      duration: 200,
      // 定义动画效果，当前是匀速
      timingFunction: 'linear'
    })
    // 将该变量赋值给当前动画
    that.animation = animation
    // 先在y轴偏移，然后用step()完成一个动画
    animation.translateY(440).step()
    // 用setData改变当前动画
    that.setData({
      // 通过export()方法导出数据
      animationData: animation.export(),
      showProp: true,
    })
    // 设置setTimeout来改变y轴偏移量，实现有感觉的滑动
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export()
      })
    }, 200)
  },
  //关闭弹窗动画
  closePopAnima: function(e) {
    var that = this;
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear'
    })
    that.animation = animation
    animation.translateY(440).step()
    that.setData({
      animationData: animation.export()

    })
    setTimeout(function() {
      animation.translateY(0).step()
      that.setData({
        animationData: animation.export(),
        showProp: false
      })
    }, 200)
  },
  //去下单
  onBuy(e) {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //返回
  onBack(e) {
    wx.navigateBack({
      dealta: 1
    })
  },
  //攻略
  onStrategy(e) {
    wx.navigateTo({
      url: '/pages/game/game_strategy/game_strategy',
    })
  },
  onClose1(e) {
    this.setData({
      showlead1: 1
    })
    wx.setStorageSync("step1", 1)
  },
  onClose2(e) {
    this.setData({
      showlead2: 1
    })
    wx.setStorageSync("step2", 1)
  },
  onClose3(e) {
    this.setData({
      showlead3: 1
    })
    wx.setStorageSync("step3", 1)
  },
  onClose4(e) {
    this.setData({
      showlead4: 1
    })
    wx.setStorageSync("step4", 1)
  },
  onClose5(e) {
    this.setData({
      showlead5: 1
    })
    wx.setStorageSync("step5", 1)
  },
  //背景音乐
  backmusic: function () {
    player();

    function player() {
      bgm.title = "BGM "; // 必须要有一个title
      bgm.src = "https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/%E7%BA%AF%E9%9F%B3%E4%B9%90%20-%20%E5%AD%94%E9%9B%80.mp3";
      bgm.onEnded(() => {
        player(); // 音乐循环播放

      })

    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    bgm.stop();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(mySetInterval);
    bgm.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: "傣王稻勐海香米，一键领取优惠",
      path: '/pages/game/game_index/game_index?userid=' + wx.getStorageSync("userid"),
      imageUrl: 'https://zebra-1258707023.cos.ap-chengdu.myqcloud.com/yndwd/game-play-bg.jpg'
    }
  }
})